//
//  JUser.swift
//  JMicroBlog
//
//  Created by Jason on 19/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
import Alamofire
class JAccount: NSObject, NSCoding{
   
    // MARK: - 属性
    // 用于调用access_token，接口获取授权后的access token。
    let access_token:String
    
    // access_token的生命周期，单位是秒数。
    let expires_in : NSTimeInterval
    
    // 过期日期
    var expires_date : NSDate
    
    // 当前授权用户的UID
    let uid : String
    
    // 以下两个属性不能在初始化获得
    // 用户信息
    var name : String?
    
    // 用户头像
    var avatar_large : String?
    
    // access_token的保存路径
    static let accountInfoPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("accountInfo.plist")
    
    // MARK: - 关键方法
    init(dict:[String:AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
        uid = dict["uid"] as! String
    }
    
    /**
    获取授权的Access_Token
    
    :param: params 要获得Access_Token时需要向服务器发送的字典消息
    */
    class func loadAccessToken(params:[String:String],completion:(account:JAccount?,error:NSError?)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        JNetworkTools.responseJSON(.POST, URLString: urlString, params: params) { (JSON) -> () in
            JLog.i(JSON,false)
            if JSON != nil {
                // 字典转模型
                let account = JAccount(dict: JSON as! [String:AnyObject])
                
                // 加载用户信息
                account.loadUserInfo(completion)
            }
            
            JLog.i("\(NSHomeDirectory())",false)
        }
    }
    
    /** 加载用户信息 */
    func loadUserInfo(completion:(account:JAccount?,error:NSError?)->()) {
        
        // 获得用户信息的请求页面
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["access_token":access_token,"uid":uid]
        
        // 发送请求
        JNetworkTools.responseJSON(.GET, URLString: urlString, params: params) { JSON in
          JLog.i(JSON!,false)
          if JSON != nil {
            // 给对象赋值
            if let dict = JSON as? [String:AnyObject] {
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                // 归档
                NSKeyedArchiver.archiveRootObject(self, toFile: JAccount.accountInfoPath)
                // 回调
                completion(account: self, error: nil)
            } else {
                // 如果服务器返回的不是JSON格式的字典(可能性很低)
                let jsonError = NSError(domain: "Jweibo.user", code: -520, userInfo:["error":"json格式错误"])
                completion(account: nil, error: jsonError)
            }
          }
        }
    }
    
    /**
    从沙盒中加载用户信息
    
    :returns: 返回用户信息
    */
    class func loadUserInfo() -> JAccount?{
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(JAccount.accountInfoPath) as? JAccount {
            // 用户的accessToken是否已经过期
            if account.expires_date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
    }
    
    // MARK: - 归档与解档
    
    /**
    归档方法
    
    :param: aCoder 归档器
    */
    func encodeWithCoder(aCoder: NSCoder) {
      aCoder.encodeObject(access_token, forKey: "access_token")
      aCoder.encodeDouble(expires_in, forKey: "expires_in")
      aCoder.encodeObject(expires_date, forKey: "expires_date")
      aCoder.encodeObject(uid, forKey: "uid")
      aCoder.encodeObject(name,forKey:"name")
      aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /**
    解档方法
    
    :param: aDecoder 解档器
    
    :returns: 返回解档后的对象
    */
    required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        expires_date = aDecoder.decodeObjectForKey("expires_date") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
}
// MARK: - Printable协议
/**在swift中要实现description的功能需要遵守Printable协议 */
extension JAccount : Printable {
    override var description : String {
        let attrs = ["access_token","expires_in","uid","expires_date","name","avatar_large"]
        return "\(dictionaryWithValuesForKeys(attrs))"
    }
}
